<template>
  <div>
    <el-dialog
      modal-class="allroun-dialog"
      v-model="_isOpen"
      width="520"
      align-center
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancelClick"
    >
      <template #header>
        <h4>{{ optionInfo.type === "add" ? "添加综合项" : "编辑综合项" }}</h4>
      </template>
      <template #default>
        <el-form :model="form" ref="formRef" label-width="500px" label-position="left">
          <el-form-item label="综合项名称" prop="itemName" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input v-model="form.itemName" placeholder="请输入综合名称" />
          </el-form-item>
          <el-form-item
            label="计费方式"
            prop="moneyType"
            :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
          >
            <el-radio-group v-model="form.moneyType">
              <el-radio :value="1">比例费用</el-radio>
              <el-radio :value="2">固定费用</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.moneyType === 1">
            <el-form-item label="费用比例" prop="feeRate" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
              <el-input
                v-model="form.feeRate"
                placeholder="请输入费用比例"
                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              >
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="关联报价"
              prop="linkTypes"
              :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
            >
              <el-checkbox-group v-model="form.linkTypes">
                <el-checkbox :label="'主材'" value="1" />
                <el-checkbox :label="'辅材'" value="2" />
                <el-checkbox :label="'人工'" value="3" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              label="费用关联空间"
              prop="linkSpces"
              :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
            >
              <template #label>
                <p class="mr20">费用关联空间</p>
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
              </template>
              <el-checkbox-group v-model="form.linkSpces" @change="handleCheckedChange">
                <el-checkbox v-for="item in spaceList" :key="item.spaceId" :label="item.spaceName" :value="item.spaceId" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              label="自动关联新增空间"
              prop="isAutoNewSpace"
              :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
            >
              <template #label>
                <p class="mr10">自动关联新增空间</p>
                <el-switch v-model="form.isAutoNewSpace" :active-value="1" :inactive-value="0" class="mr10" />
                <i class="f12" style="font-style: normal; color: #86909c">注：开启后，预算新增空间时，自动统计到该综合项中</i>
              </template>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item label="费用金额" prop="itemMoney" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
              <el-input
                v-model="form.itemMoney"
                placeholder="请输入费用金额"
                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              >
                <template #suffix>元</template>
              </el-input>
            </el-form-item>
          </template>
          <el-form-item label="综合项备注" prop="remark" :rules="{ required: false, message: '请输入', trigger: ['blur'] }">
            <el-input :rows="2" maxlength="200" type="textarea" v-model="form.remark" placeholder="请输入"> </el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <div style="flex: auto">
            <el-button type="info" @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">确认</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import { comprehensiveAdd, comprehensiveUpd } from "@/apis/quote-price/following";

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        type: "",
        detail: {},
        spaceList: [],
        currTempObj: {}
      };
    }
  }
});
const form = ref({ isAutoNewSpace: 0, moneyType: 1 });
const formRef = ref();
const checkAll = ref(false);
const isIndeterminate = ref(false);
const spaceList = ref([]);

watch(
  () => props.optionInfo.detail._time,
  val => {
    console.log("传递过来的综合项数据", props.optionInfo);
    spaceList.value = props.optionInfo.spaceList || [];
    if (props.optionInfo.type === "edit") {
      const _detail = JSON.parse(JSON.stringify(props.optionInfo.detail));
      form.value = _detail;
      form.value.linkTypes = _detail.linkTypes ? _detail.linkTypes.split(",") : [];
      form.value.linkSpces = _detail.linkSpces ? _detail.linkSpces.split(",") : [];
      delete form.value._time;
      handleCheckedChange(form.value.linkSpces);
    }
  },
  { deep: true, immediate: false }
);
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

const handleCheckAllChange = val => {
  form.value.linkSpces = val ? spaceList.value.map(item => item.spaceId) : [];
  isIndeterminate.value = false;
};
const handleCheckedChange = val => {
  const checkedCount = val.length;
  checkAll.value = checkedCount === spaceList.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < spaceList.value.length;
};

const cancelClick = () => {
  form.value = { isAutoNewSpace: 0, moneyType: 1 };
  formRef.value.resetFields();
  checkAll.value = false;
  isIndeterminate.value = false;
  _isOpen.value = false;

  // emit("submitOk");
};
const confirmClick = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if ((Number(form.value.feeRate) > 10000 || Number(form.value.feeRate) < 0) && form.value.moneyType === 1) {
        ElMessage({
          message: "费用比例必须在0-10000之间",
          type: "error"
        });
        return;
      }
      const params = {
        ...form.value,
        linkSpces: form.value.linkSpces ? form.value.linkSpces.join(",") : "",
        linkTypes: form.value.linkTypes ? form.value.linkTypes.join(",") : ""
      };
      if (form.value.moneyType === 1) {
        //比例费用
        params.itemMoney = "";
        // params.remark = "";
      } else if (form.value.moneyType === 2) {
        //固定费用
        params.feeRate = "";
        params.linkSpces = "";
        params.linkTypes = "";
        params.isAutoNewSpace = null;
      }
      if (props.optionInfo.type === "add") {
        // 添加
        comprehensiveAdd({
          budgetId: props.optionInfo.currTempObj.budgetId, //报价id
          ...params
        }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "综合项添加成功",
              type: "success"
            });
            cancelClick();
            emit("submitOk");
          }
        });
      } else {
        // 修改
        comprehensiveUpd({
          ...params
        }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "综合项修改成功",
              type: "success"
            });
            cancelClick();
            emit("submitOk");
          }
        });
      }
    } else {
      console.log("error submit!");
    }
  });
};

defineExpose({});
</script>

<style lang="scss">
.allroun-dialog {
  .el-dialog {
    padding-left: 0 !important;
    padding-right: 0 !important;
    padding-bottom: 0 !important;
    .el-dialog__header {
      border-bottom: 1px solid #e2e8f0;
      padding: 0 24px 20px 24px;
    }
    .el-dialog__body {
      padding: 20px;
      .el-form-item {
        flex-direction: column;
      }
    }
    .el-dialog__footer {
      padding-top: 0;
      text-align: center;
    }
  }
  .dialog-footer {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    margin: 0;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
<style lang="scss" scoped>
.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}
.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;
  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
</style>
